import { Controller, Post, Body, UseInterceptors, UploadedFile } from '@nestjs/common';
import { FileInterceptor } from '@nestjs/platform-express';
import { diskStorage } from 'multer';
import { extname } from 'path';
import * as fs from 'fs';
import * as sharp from 'sharp';

@Controller('upload')
export class UploadController {
    @Post()
    @UseInterceptors(
        FileInterceptor('file', {
            storage: diskStorage({
                destination: process.env.FILE_PATH || './uploads',
                filename: (req, file, callback) => {
                    const timestamp = Date.now();
                    const ext = extname(file.originalname);
                    callback(null, `${timestamp}${ext}`);
                },
            }),
            limits: {
                fileSize: 20 * 1024 * 1024, // 限制为20MB
            },
        }),
    )
    async uploadFile(@UploadedFile() file: any) {
        // 检查是否为图片文件
        const imageExtensions = ['.jpg', '.jpeg', '.png', '.gif', '.webp'];
        const ext = extname(file.originalname).toLowerCase();
        let thumbnailPath = '';
        let thumbnailName = ''
        if (imageExtensions.includes(ext)) {
            const timestamp = file.filename.split('.')[0];
            thumbnailName = `${timestamp}.min${ext}`;
            console.log("thumbnailName", thumbnailName);
            thumbnailPath = `${process.env.FILE_PATH}/${thumbnailName}`;

            // 生成缩略图
            await sharp(file.path)
                .resize(300, 300, {
                    fit: 'inside',      // 保持宽高比
                    withoutEnlargement: true  // 不放大小图片
                })
                .toFile(thumbnailPath);
        }
        return {
            thumbnail: `${process.env.ASSETS_URL}/${thumbnailName}`,
            path: `${process.env.ASSETS_URL}/${file.filename}`,
            host: `${process.env.ASSETS_URL}`,
            name: `${file.filename}`
        }
    }

    @Post("/base64")
    base64(@Body() obj: any) {
        console.log("base64 name", obj.name);
        const base64Data = obj.image.split(';base64,').pop(); // 解析出真正的 base64 数据部分
        const buffer = Buffer.from(base64Data, 'base64'); // 将 base64 转换为 Buffer

        const name = `tmp_${Date.now()}.png`;
        // 写入文件
        fs.writeFileSync(`${process.env.FILE_PATH}/${name}`, buffer);
        console.log("name", name);

        return { path: `${process.env.ASSETS_URL}/${name}` };
    }

}